package net.lzzy.upload_download.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
public class FileController {

    private static final String dirPath = "E:/";

    @GetMapping("/upload")
    public String upLoad(){
        return "upload";
    }
    @PostMapping("/upload")
    public String upLoadFile(MultipartFile[] files, Model model){

        for(MultipartFile file:files){
            if(!file.isEmpty()){
                String fileName = file.getOriginalFilename();

                File filePath=new File(dirPath);
                if(!filePath.exists()){
                    if(!filePath.mkdirs()){
                        model.addAttribute("msg","创建目录失败");
                        return "upLoad";
                    }
                }
                File newFile=new File(dirPath+fileName);
                if(newFile.exists()){
                    model.addAttribute("msg","已有同名文件存在");
                    return "upLoad";
                }
                //上传文件
                try{
                    file.transferTo(newFile);
                }catch(Exception e){
                    model.addAttribute("msg","上传失败"+e.getMessage());
                }
                model.addAttribute("msg","上传成功");
            }
            else{
                model.addAttribute("msg","请选择上传文件");
            }
        }
        return "upLoad";
            }

}
